/**
 * Created by lucas on 2017/4/6.
 */


import java.io.*;
import java.net.*;
import java.util.logging.Logger;

public class HttpRequestUtil {

    private static final Logger logger = Logger.getLogger(HttpRequestUtil.class.getName());

    public static String sendGetWithProxy(String url, String host, String port) {
        SocketAddress addr = new InetSocketAddress(host, Integer.parseInt(port));
        Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
        StringBuffer html = new StringBuffer();
        String result = null;
        try {
            String urlName = url;
            URL realUrl = new URL(urlName);
            //打开和URL之间的连接
            URLConnection conn = realUrl.openConnection(proxy);
            //设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(15000);
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            //建立实际的连接
            conn.connect();
            BufferedInputStream in = new BufferedInputStream(conn.getInputStream());


            try {
                String inputLine;
                byte[] buf = new byte[4096];
                int bytesRead = 0;
                while (bytesRead >= 0) {
                    inputLine = new String(buf, 0, bytesRead, "ISO-8859-1");
                    html.append(inputLine);
                    bytesRead = in.read(buf);
                    inputLine = null;
                }
                buf = null;
            } finally {
                in.close();
                conn = null;
                url = null;
            }
            result = new String(html.toString().trim().getBytes("ISO-8859-1"), "utf-8").toLowerCase();
        } catch (Exception e) {
            //logger.info("发送GET请求出现异常！"+proxy +" " + result);
        }
        return result;
    }

    public static String sendGet(String url) {

        StringBuffer html = new StringBuffer();
        String result = null;
        try {
            String urlName = url;
            URL realUrl = new URL(urlName);
            //打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            //设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(15000);
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            //建立实际的连接
            conn.connect();
            BufferedInputStream in = new BufferedInputStream(conn.getInputStream());

            try {
                String inputLine;
                byte[] buf = new byte[4096];
                int bytesRead = 0;
                while (bytesRead >= 0) {
                    inputLine = new String(buf, 0, bytesRead, "ISO-8859-1");
                    html.append(inputLine);
                    bytesRead = in.read(buf);
                    inputLine = null;
                }
                buf = null;
            } finally {
                in.close();
                conn = null;
                url = null;
            }
            result = new String(html.toString().trim().getBytes("ISO-8859-1"), "utf-8").toLowerCase();
        } catch (Exception e) {
//            System.out.println("发送GET请求出现异常！" + e);
        }
        return result;
    }

//    public static String sendGet(String url) {
//        String result = null;
//        BufferedReader in = null;
//        try {
//            String urlName = url;
//            URL realUrl = new URL(urlName);
//            //打开和URL之间的连接
//            URLConnection conn = realUrl.openConnection();
//            //设置通用的请求属性
//            conn.setRequestProperty("accept", "*/*");
//            conn.setRequestProperty("connection", "Keep-Alive");
//            conn.setRequestProperty("user-agent",
//                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
//            conn.setReadTimeout(15000);
//            //建立实际的连接
//
//            conn.connect();
//            conn.setConnectTimeout(2000);
//
//            //定义BufferedReader输入流来读取URL的响应
//            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
//            String line;
//            while ((line = in.readLine()) != null) {
//                result += line;
//            }
//        } catch (Exception e) {
//            logger.info("发送GET请求出现异常！" + e);
//        }
//        //使用finally块来关闭输入流
//        finally {
//            try {
//                if (in != null) {
//                    in.close();
//                }
//            } catch (IOException ex) {
//                ex.printStackTrace();
//            }
//        }
//        return result;
//    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    public static void main(String args[]) {
        String ret = sendGetWithProxy("http://1212.ip138.com/ic.asp", "180.122.20.71", "20151");
        //String ret = sendGet("http://1212.ip138.com/ic.asp");
        System.out.print(ret);
    }
}
